package website.caidabao.blog.thymeleaf.service;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import java.io.File;
import java.io.PrintWriter;
import java.util.Map;
@Service
public class thymeleafService {
    @Autowired
    private ArticleService articleService;

    @Autowired
    private TemplateEngine templateEngine;

    private static final Logger LOGGER = LoggerFactory.getLogger(thymeleafService.class);

    /**
     * 创建html页面
     *
     * @param Id
     * @throws Exception
     */
    public void createHtml(Long Id) {

        PrintWriter writer = null;
        try {
            // 获取页面数据
            Map<String, Object> Map = this.articleService.loadModel(Id);

            // 创建thymeleaf上下文对象
            Context context = new Context();
            // 把数据放入上下文对象
            context.setVariables(Map);

            // 创建输出流
            File file = new File("E:\\caidabao_blog\\portal\\" + Id + ".html");
            writer = new PrintWriter(file);

            // 执行页面静态化方法
            templateEngine.process("readTemplate", context, writer);
        } catch (Exception e) {
            LOGGER.error("页面静态化出错：{}，"+ e, Id);
        } finally {
            if (writer != null) {
                writer.close();
            }
        }
    }
}
